package Q100;

import com.sun.source.tree.Tree;

import java.util.*;

/**
 * 判断是否是相同的树
 */
public class Test {
    public static void main(String[] args) {
        TreeNode treeNode = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        treeNode.left = treeNode2;
        treeNode.right = treeNode3;

        TreeNode treeNode4 = new TreeNode(1);
        TreeNode treeNode5 = new TreeNode(2);
        TreeNode treeNode6 = new TreeNode(3);
        treeNode4.left = treeNode5;
        treeNode4.right = treeNode6;

        System.out.println(new Solution().isSameTree(treeNode, treeNode4));
    }
}


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }
}

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null || q == null) return false;
        boolean flag = false;
        int[] ints = loadTree(p);
//        for (int i = 0; i < ints.length; i++) {
//            System.out.println(ints[i]);
//        }
//        System.out.println("----------------");
        int[] ints1 = loadTree(q);
//        for (int i = 0; i < ints1.length; i++) {
//            System.out.println(ints1[i]);
//        }

        //判断两个数组相同的方法（原始)
//        for (int i = 0; i < ints.length; i++) {
//            if (ints[i] == ints1[i]) flag = true;
//            else {
//                return false;
//            }
//        }
        return Arrays.equals(ints,ints1);
    }
    public int[] loadTree(TreeNode root) {
        if (root == null) {
            return new int[0];
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        List<TreeNode> list = new ArrayList<>();
        while (!queue.isEmpty()) {
            TreeNode poll = queue.poll();
            list.add(poll);
            if (poll.left != null) {
                queue.add(poll.left);
            }
            if (poll.right != null){
                queue.add(poll.right);
            }
        }
        int[] ints = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ints[i] = list.get(i).val;
        }
        return ints;
    }


    /**
     * 递归算法
     * @param p
     * @param q
     * @return 两棵树是否相同
     */
    public boolean isSameTree2(TreeNode p, TreeNode q) {
        if(p==null && q==null){
            return true;
        }
        if(p!=null && q!=null && p.val==q.val  ){
            return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
        }else {
            return false;
        }
    }
}
